package apiWeb

import (
	"fmt"

	liveResource "ZHONGYIHANGYAN/business/liveResource"
	quota "ZHONGYIHANGYAN/business/quota"
	template "ZHONGYIHANGYAN/business/template"
	terminalResource "ZHONGYIHANGYAN/business/terminalResource"
	vodResource "ZHONGYIHANGYAN/business/vodResource"
	user "ZHONGYIHANGYAN/business/user"
	role "ZHONGYIHANGYAN/business/role"
	evaluateTask "ZHONGYIHANGYAN/business/evaluateTask"

	"ZHONGYIHANGYAN/cfg"
	projCom "ZHONGYIHANGYAN/commUtils/projComm"
	"ZHONGYIHANGYAN/web"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

type webServer interface {
	RegVersion(version gin.HandlerFunc)
	RegSystemConfigData(config gin.HandlerFunc)
	RegSystemDefaultData(version gin.HandlerFunc)
	RegRouters(handle ...func(*gin.RouterGroup))
	GetPayload(c *gin.Context, out interface{}) error
}

type Api struct {
	// 模板管理对象
	templateManage *template.TemplateManage
	// 指标管理对象
	quotaManage *quota.QuotaManage
	// 直播资源管理对象
	liveResourceManage *liveResource.LiveResourceManage
	// 点播资源管理对象
	vodResourceManage *vodResource.VodResourceManage
	// 终端资源管理对象
	terminalResourceManage *terminalResource.TerminalResourceManage
	// 用户管理对象
	userManage *user.UserManage
	// 角色管理对象
	roleManage *role.RoleManage
	// 评价任务管理对象
	evaluateTaskManage *evaluateTask.EvaluateTaskManage

	web                    webServer
}

func New(w webServer) *Api {
	api := new(Api)
	api.web = w

	// 版本号
	api.web.RegVersion(web.NewWebRouter(api.getVersion).Func)

	// 系统内置配置
	api.web.RegSystemConfigData(web.NewWebRouter(api.getSystemConfigData).Func)

	// 系统内置数据
	api.web.RegSystemDefaultData(web.NewWebRouter(api.getSystemDefaultData).Func)

	// 注册库存管理业务相关路由
	api.InitTemplateRouter()
	api.InitQuotaRouter()
	api.InitLiveResourceRouter()
	api.InitVodResourceRouter()
	api.InitTerminalResourceRouter()
	api.InitUserRouter()
	api.InitRoleRouter()
	api.InitEvaluateTaskRouter()
	return api
}

/*
 * 参数校验
 */
func validateParam(info interface{}) error {
	validate := validator.New()
	if err := validate.Struct(info); err != nil {
		// 临时打印不合法参数
		if errs, ok := err.(validator.ValidationErrors); ok {
			for _, e := range errs {
				fmt.Printf("Field: %s, Tag: %s, Value: %s\n", e.Field(), e.Tag(), e.Value())
			}
		}
		return fmt.Errorf("%w参数不合法", projCom.ErrAll)
	}
	return nil
}

/* 获取系统版本 */
func (a *Api) getVersion(c *gin.Context, replayData *interface{}) error {
	*replayData = cfg.Ver
	return nil
}

/* 获取系统内置配置 */
func (a *Api) getSystemConfigData(c *gin.Context, replayData *interface{}) error {
	*replayData = map[string]interface{}{
		"finalScoreCountdown": cfg.Sys.FinalScoreCountdown,
	}
	return nil
}

// 获取系统内置数据
func (a *Api) getSystemDefaultData(c *gin.Context, replayData *interface{}) error {
	*replayData = cfg.Data
	return nil
}
